'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { 
  TextField, 
  Button, 
  Card, 
  CardContent, 
  Typography, 
  Box, 
  Alert, 
  Stepper,
  Step,
  StepLabel,
  CircularProgress
} from '@mui/material';
import PhoneVerificationForm from '@/app/components/PhoneVerificationForm';

export default function ResetPasswordWithPhonePage() {
  const router = useRouter();
  const [activeStep, setActiveStep] = useState(0);
  const [verifiedPhone, setVerifiedPhone] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  
  const [formData, setFormData] = useState({
    newPassword: '',
    confirmPassword: '',
  });
  
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleVerificationSuccess = (phone: string, code: string) => {
    setVerifiedPhone(phone);
    setVerificationCode(code);
    setActiveStep(1);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setSuccess('');
    setLoading(true);

    // 基本验证
    if (formData.newPassword !== formData.confirmPassword) {
      setError('两次输入的密码不一致');
      setLoading(false);
      return;
    }

    if (formData.newPassword.length < 6) {
      setError('密码长度至少为6个字符');
      setLoading(false);
      return;
    }

    try {
      const response = await fetch('/api/auth/reset-password-with-phone', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          phone: verifiedPhone,
          code: verificationCode,
          newPassword: formData.newPassword
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || '重置密码失败');
      }

      setSuccess('密码重置成功！正在跳转到登录页面...');
      
      // 延迟跳转到登录页面
      setTimeout(() => {
        router.push('/auth/login');
      }, 2000);
    } catch (err) {
      setError(err instanceof Error ? err.message : '重置密码过程中发生错误');
    } finally {
      setLoading(false);
    }
  };

  const steps = ['手机验证', '重置密码'];

  return (
    <Box
      sx={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        bgcolor: 'background.default',
        py: 4,
      }}
    >
      <Card sx={{ maxWidth: 500, width: '100%', mx: 2 }}>
        <CardContent sx={{ p: 4 }}>
          <Typography variant="h4" component="h1" align="center" gutterBottom>
            手机号重置密码
          </Typography>
          
          <Stepper activeStep={activeStep} sx={{ mb: 4, mt: 2 }}>
            {steps.map((label) => (
              <Step key={label}>
                <StepLabel>{label}</StepLabel>
              </Step>
            ))}
          </Stepper>

          {activeStep === 0 && (
            <PhoneVerificationForm 
              purpose="password_reset"
              onVerificationSuccess={handleVerificationSuccess}
            />
          )}

          {activeStep === 1 && (
            <form onSubmit={handleSubmit}>
              <TextField
                fullWidth
                label="新密码"
                type="password"
                name="newPassword"
                value={formData.newPassword}
                onChange={handleChange}
                margin="normal"
                required
                autoComplete="new-password"
              />
              
              <TextField
                fullWidth
                label="确认新密码"
                type="password"
                name="confirmPassword"
                value={formData.confirmPassword}
                onChange={handleChange}
                margin="normal"
                required
                autoComplete="new-password"
              />

              {error && (
                <Alert severity="error" sx={{ mt: 2 }}>
                  {error}
                </Alert>
              )}

              {success && (
                <Alert severity="success" sx={{ mt: 2 }}>
                  {success}
                </Alert>
              )}

              <Button
                fullWidth
                type="submit"
                variant="contained"
                size="large"
                sx={{ mt: 3 }}
                disabled={loading}
              >
                {loading ? <CircularProgress size={24} /> : '重置密码'}
              </Button>

              <Box sx={{ mt: 2, textAlign: 'center' }}>
                <Link href="/auth/login" style={{ textDecoration: 'none' }}>
                  <Typography color="primary">
                    返回登录
                  </Typography>
                </Link>
              </Box>
            </form>
          )}
        </CardContent>
      </Card>
    </Box>
  );
}
